package com.imesne.office.excel.write;

import com.imesne.office.excel.exception.OfficeException;
import com.imesne.office.excel.model.ExcelBook;
import com.imesne.office.excel.model.ExcelSheet;
import com.imesne.office.excel.model.ExcelVersion;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collection;

/**
 * Created by liyd on 17/7/4.
 */
public class ExcelBookWriterImpl extends AbstractConfigWriter implements ExcelBookWriter {

    public Workbook writeExcelBook(ExcelBook excelBook, byte[] existFileBytes) {

        ExcelWriterConfig excelWriterConfig = this.getExcelWriterConfig();

        Workbook workbook;
        try {

            if (ExcelVersion.XLSX == excelWriterConfig.getVersion()) {
                workbook = ArrayUtils.isEmpty(existFileBytes) ? new XSSFWorkbook() : new XSSFWorkbook(new ByteArrayInputStream(existFileBytes));
            } else {
                workbook = ArrayUtils.isEmpty(existFileBytes) ? new HSSFWorkbook() : new HSSFWorkbook(new ByteArrayInputStream(existFileBytes));
            }
        } catch (IOException e) {
            throw new OfficeException("创建excel文件失败", e);
        }

        ExcelSheetWriter excelSheetWriter = excelWriterConfig.getExcelSheetWriter();
        Collection<ExcelSheet> excelSheets = excelBook.getExcelSheets();
        int count = 1;
        for (ExcelSheet excelSheet : excelSheets) {
            excelSheetWriter.writeExcelSheet(workbook, excelSheet, count++);
        }
        if (excelWriterConfig.getExcelWriteProcessor() != null) {
            excelWriterConfig.getExcelWriteProcessor().processWorkbook(excelBook, workbook);
        }
        return workbook;
    }
}
